import EXIF from 'exif-js'
import axios from 'axios'

// 发送请求
export function myPost(request, data, func, baseURL = URLheader, method = 'post') {
  // console.log("请求", URLheader + request, data)
  axios({
    baseURL, method,
    headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" },
    url: request, data: data,
  })
    .then(res => {
      func && func(res.data)
    })
    .catch(function (error) {
      console.warn(error)
    })
}

// 获取链接后的参数(不带#号)
export function getQueryString() {
  let href = window.location.href
  let hash = href.slice(href.lastIndexOf('#') + 1, href.length), i
  let a = {}
  for (const s of hash.split('&')) a[s.split('=')[0]] = s.split('=')[1]
  return a;
}


// 标签简写转全
export function classToAll(c) {
  return { "js": "技术", "wx": "文学", "yl": "娱乐", "qt": "其他", "xy": "校园" }[c]
}

// 给一个元素id，滚动条跳转
export function goAnchor(e) {
  document.querySelector("#" + e).scrollIntoView({
    behavior: "smooth", block: "center", inline: "nearest",
  })
}

// 获取URL参数
export function getQueryAttr(variable) {
  let vars = window.location.href.substring(window.location.href.indexOf("?") + 1).split("&");
  for (const value of vars) {
    if (value.split("=")[0] == variable) return value.split("=")[1];
  }
  return undefined
}


// 将字符串传入剪贴板
export function writeClipboard(str, func) {
  const clipboardObj = navigator.clipboard;
  if (!clipboardObj) { console.warn('浏览器不支持 navigator.clipboard'); return false }
  navigator.clipboard.writeText(str).then(
    () => func && func(),
    error => console.log(error)
  )
}



// 图片压缩==============================================
export function compressImg(file, rate = 0.2) {
  let disposeFile = file;

  // 判断 gif
  if (file.type == 'image/gif') {
    console.log("压缩完成：gif图片直接输出")
    return new Promise((resolve, reject) => {
      resolve(disposeFile);
    });
  }

  if (Object.prototype.toString.call(file) === '[object Blob]') {
    disposeFile = new File([file], file.name, { type: file.type });
  }
  const read = new FileReader()
  const fileSize = parseFloat(parseInt(disposeFile['size']) / 1048576).toFixed(2);
  // 小于1m不压缩
  // if (fileSize < 1) return file;
  read.readAsDataURL(disposeFile);
  return new Promise((resolve, reject) => {

    try {
      read.onload = (e) => {
        const img = new Image();
        img.src = e.target.result;
        img.onload = function () {
          let w = Math.floor(this.width / 2), h = Math.floor(this.height / 2);
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          let base64;
          canvas.setAttribute('width', w);
          canvas.setAttribute('height', h);
          ctx.drawImage(this, 0, 0, w, h);
          // console.log(w, h);
          base64 = canvas.toDataURL(disposeFile['type'], rate);

          let overImg = dataURLtoFile(base64, disposeFile.name)
          // console.log("压缩完成，压缩前：" + file.size / 1048576 + " 压缩后：" + overImg.size / 1048576)
          resolve(overImg);
        };
      };
    } catch (error) {
      reject(disposeFile);
    }

  });
}

function dataURLtoFile(dataurl, fileName) {
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], fileName, {
    type: mime,
  });
}

// 文件URL转 File
// 输入url和文件名，返回File对象，是异步操作
export function getFileFromUrl(url, fun, fileName) {
  if (!fileName) fileName = url.split('/').pop()
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url);
  xhr.setRequestHeader('Accept', 'image/png');
  xhr.responseType = "blob";
  // 加载时处理
  xhr.onload = () => {
    // 获取返回结果
    let file = new File([xhr.response], fileName, { type: 'image/png' });
    fun(file);
  };
  xhr.onerror = e => fun(e)
  // 发送
  xhr.send();
}


// 传入图片文件，返回图片EXIF信息===========================================
// 提取EXIF信息，写入文件属性中，并返回给回调
export function getExifFromFile(file, fun) {
  try {
    window.n = 0; // exif-js 自身的bug修复
    EXIF.getData(file, function () {
      fun && fun(EXIF.getAllTags(this))
    })
  } catch (e) {
    console.error(e)
  }
}

// 传入URL，返回图片EXIF信息
export function getExifFromURL(url, fun) {
  getFileFromUrl(url, file => {
    getExifFromFile(file, exif => fun(exif))
  })
}





/**
 * Base64 编码/解码
 */
export function Encode64(str) { // 编码
  return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
    function toSolidBytes(match, p1) {
      return String.fromCharCode('0x' + p1);
    }));
}

export function Decode64(str) { // 解码
  return decodeURIComponent(atob(str).split('').map(function (c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));
}